/**
 * 通用方法封装处理， 需要跟后台交互的js都不能写在此处，依赖layer,
 */
;!function($, window) {
	//全局layer对象
	var layer = window.layer;
	var parentLayer = window.parent.layer;
	
	/*获取当前widown的layer对象 */
	window.getCurLayer = function() {
		return layer;
	}
	
	/*iframe获取父窗口的layer对象 */
	window.getParenLayer = function() {
		return parentLayer;
	}
	
	//表单内部取消按钮
	$('#cancel-but').click(function() {
		var index = parentLayer.getFrameIndex(window.name);
		parentLayer.close(index);
	});
	
	//表单内存提交按钮
	$('#b-btn-save').click(function() {
		$('form').submit();
	});
	
	//隐藏查询条件效果
	$('button[data-widget="collapse"]').click(function() {
		var $faIcon = $(this).children('i').first(); 
		var flag = $faIcon.hasClass('fa-minus');
		if(flag) {
			$faIcon.removeClass('fa-minus').addClass('fa-plus');
		} else {
			$faIcon.removeClass('fa-plus').addClass('fa-minus');		
		}
		$(this).parents('.box').first().find('.form-body').toggle('slow'); 
	});
	
	/*工具类 */
	window.util = {
		trim: function(value) {
			if(value == null) {
				return '';
			}
            return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, '');
		},
		isEmpty: function(value) {
			if(value == null || this.trim(value) == '') {
				return true;
			}
			return false;
		},
		/*parent true 则返回父layer，否则返回当前layer */
		getLayer: function(parent) {
			if(parent) {
				return getParenLayer();
			}
			return getCurLayer();
		}
	}
	
	/*js扩展方法 */
	$.extend({
		
		
		
		modal: {
			
			// 弹出层指定宽度
            open: function (options) {
            	//title, url, width, height, parent
            	var title = options.title;
            	var url = options.url;
            	var width = options.width;
            	var height = options.height;
            	var parent = options.parent;
            	//如果是移动端，就使用自适应大小弹窗
            	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            	    width = 'auto';
            	    height = 'auto';
            	}
            	if (util.isEmpty(title)) {
                    title = false;
                };
                if (util.isEmpty(url)) {
                    url = "/404.html";
                };
                if (util.isEmpty(width)) {
                	width = 800;
                };
                if (util.isEmpty(height)) {
                	height = ($(window).height() - 150);
                };
				var layer = util.getLayer(parent);
            	layer.open({
            		type: 2,
            		area: [width + 'px', height + 'px'],
            		fix: false,
            		//不固定
            		maxmin: true,
            		shade: 0.3,
            		title: title,
            		content: url,
            	    // 弹层外区域关闭
            		shadeClose: true,
            		btn: options.btn,
            		yes: options.yes,
            	    cancel: options.cancel,
            	    end: options.end
            	});
            },
			
		}
		
	});
	
	/*扩展jquery 元素方法 */
	$.fn.extend({
		
		//表单序列化成json
		serializeJson: function() {
			var serializeObj = {};
			var array = this.serializeArray();
			$(array).each(
					function() {
						if (serializeObj[this.name]) {
							if ($.isArray(serializeObj[this.name])) {
								serializeObj[this.name].push(this.value);
							} else {
								serializeObj[this.name] = [serializeObj[this.name], this.value];
							}
						} else {
							serializeObj[this.name] = this.value;
						}
					});
			return serializeObj;
		},
		
		//初始化jqgrid
		initJqgrid: function(arg) {
			if(arg.rowNum == null) {
				arg.rowNum = 15;
			}
			if(arg.rowList == null) {
				arg.rowList = [10, 15, 25, 35, 50, 100];
			}
			if(arg.pager == null) {
				arg.pager = '#pager'
			}
			if(arg.multiselect == null) {
				arg.multiselect = true;
			}
			if(arg.multiboxonly == null) {
				arg.multiboxonly = true;
			}
			if(arg.height == null) {
				arg.height = $(window).height() - 240;
			}
			if(arg.dataType == null) {
				arg.dataType = 'json';
			}
			if(arg.shrinkToFit == null) arg.shrinkToFit = false;
			var $jqGrid = $(this).jqGrid( {
				url : arg.url,
				datatype : arg.dataType,
				colNames : arg.colNames,
				colModel : arg.colModel,
				rownumbers: true,
				rowNum : arg.rowNum,
				rowList : arg.rowList,
				pager : arg.pager,
				sortname : arg.sortname,
				viewrecords : true,
				sortorder : arg.sortorder,
				caption:'<i class="fa fa-list"></i> ' + arg.caption,
				shrinkToFit: arg.shrinkToFit,
				height : arg.height,
				autowidth : true,
				responsive : true,
				styleUI : 'Bootstrap',
				rownumbers: true, //设置列表显示序号,需要注意在colModel中不能使用rn作为index   
			    rownumWidth: 25, //设置显示序号的宽度，默认为25   
			    multiselect: arg.multiselect, //多选框   
			    multiboxonly: arg.multiboxonly, //在点击表格row时只支持单选，只有当点击checkbox时才多选，需要multiselect=true是有效  
				jsonReader : {
					id: arg.id, //相当于设置主键
					// 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定
					repeatitems : false
				},
				altRows:true, 
				altclass:'datagrid-row-over'
			}).navGrid(arg.pager, {
					edit : false,
					add : false,
					del : false,
					search : false,
					view : {
					    caption: 'View Record',
					    bClose: 'Close'
					  }
					});
			//添加到自定义toolbar中
			if(arg.btngroup != null) {
				$(arg.btngroup).appendTo('.ui-jqgrid-title');
			}
			
			$jqGrid.getSelIds = function(success, msg) {
				if(msg == null) {msg = '请选择记录'}
				var ids = $jqGrid.jqGrid("getGridParam","selarrrow");
				if(ids.length <= 0) {
					$.modal.alert(msg, layIcon.warn);
					return null;
				}
				if(success != null) {
					success(ids);
				}
				return ids;
			}
			$jqGrid.getSelId = function(success, msg) {
				if(msg == null) {msg = '请选择一行记录'}
				var ids = $jqGrid.jqGrid("getGridParam","selarrrow");
				if(ids.length != 1) {
					$.modal.alert(msg, layIcon.warn);
					return null;
				}
				var id = ids[0];
				if(success != null) {
					success(id);
				}
				return id;
			}
			$jqGrid.getOneData = function(success, msg) {
				var d = null;
				$jqGrid.getSelId(function(id) {
					d = $jqGrid.jqGrid('getRowData', id);
					if(success != null) {
						success(d);
					}
				}, msg);
				return d;
			}
			$jqGrid.getData = function(success, msg) {
				var data = [];
				$jqGrid.getSelIds(function(ids) {
					for(var i in ids) {
						var id = ids[i];
						var d = $jqGrid.jqGrid('getRowData', id);
						data.push(d);
					}
					if(success != null) {
						success(data);
					}
				}, msg);
				return data;
			}
			return $jqGrid;
		}
		
	});
	
}(jQuery, window);


//jquery validator 校验扩展
if($.validator != null) {
	//正则校验
	$.validator.addMethod('pattern', function(value, element, param) {
		return this.optional(element) || param.test(value);
	}, '格式不匹配');
	
	//校验中文
	$.validator.addMethod('existcn', function(value, element) {
		var pattern = /[\u4E00-\u9FA5]/i;
		return this.optional(element) || !pattern.test(value);
	}, '存在中文字符');
	
}

//配置jquery validator中文
if($.validator != null) {
	$.extend($.validator.messages, {
		required: "必填项",
		remote: "请更正此字段",
		email: "请输入有效的电子邮件地址",
		url: "请输入有效的url地址",
		date: "请输入有效的日期",
		dateISO: "请输入有效的日期 (ISO)",
		number: "请输入有效的数字",
		digits: "请输入整数",
		creditcard: "请输入一个有效的信用卡号码",
		equalTo: "请输入相同的确认值",
		accept: "请输入具有有效扩展名的值",
		maxlength: $.validator.format("请输入不超过 {0} 个字符"),
		minlength: $.validator.format("请输入至少 {0} 字符"),
		rangelength: $.validator.format("请输入介于 {0} 至 {1} 个长度的字符"),
		range: $.validator.format("请输入介于 {0} 至 {1} 的值"),
		max: $.validator.format("请输入小于等于 {0} 的值"),
		min: $.validator.format("请输入大于等于 {0} 的值")
	});
}

//bootstrap jquery validator 扩展
;!function(a){var b=0,c=0;a.extend(!0,a.validator,{prototype:{defaultShowErrors:function(){var d=this,e=a.fn.tooltip.Constructor.VERSION;e&&(e=e.split("."),b=parseInt(e[0]),c=parseInt(e[1])),a.each(this.errorList,function(e,f){if(3===b&&c>=3){var g=a(f.element);void 0!==g.data("bs.tooltip")?g.data("bs.tooltip").options.title=f.message:g.tooltip(d.applyTooltipOptions(f.element,f.message)),a(f.element).removeClass(d.settings.validClass).addClass(d.settings.errorClass).tooltip("show")}else a(f.element).removeClass(d.settings.validClass).addClass(d.settings.errorClass).tooltip(4===b?"dispose":"destroy").tooltip(d.applyTooltipOptions(f.element,f.message)).tooltip("show");d.settings.highlight&&d.settings.highlight.call(d,f.element,d.settings.errorClass,d.settings.validClass)}),a.each(d.validElements(),function(c,e){a(e).removeClass(d.settings.errorClass).addClass(d.settings.validClass).tooltip(4===b?"dispose":"destroy"),d.settings.unhighlight&&d.settings.unhighlight.call(d,e,d.settings.errorClass,d.settings.validClass)})},applyTooltipOptions:function(c,d){var e;e=4===b?a.fn.tooltip.Constructor.Default:3===b?a.fn.tooltip.Constructor.DEFAULTS:a.fn.tooltip.defaults;var f={animation:a(c).data("animation")||e.animation,html:a(c).data("html")||e.html,placement:a(c).data("placement")||e.placement,selector:a(c).data("selector")||e.selector,title:a(c).attr("title")||d,trigger:a.trim("manual "+(a(c).data("trigger")||"")),delay:a(c).data("delay")||e.delay,container:a(c).data("container")||e.container};return this.settings.tooltip_options&&this.settings.tooltip_options[c.name]&&a.extend(f,this.settings.tooltip_options[c.name]),this.settings.tooltip_options&&this.settings.tooltip_options._all_&&a.extend(f,this.settings.tooltip_options._all_),f}}})}(jQuery);
